var express = require('express');
var router = express.Router();
var db = require('../public/javascripts/db');
var config = require('../public/config');
var fs = require('fs');
const imgPath = require('../public/javascripts/config').imgPath;

// const imgPath = 'http://localhost/upload/';  //本地环境

router.post('/', function (req, res, next) {
    res.send('screening succsss');

    console.log(req.body.data.length);
    // console.log(req.body.number);
    // var addAql = `INSERT INTO history() VALUES(1, '32', 'admin', '10', 10, 'sasas', 1, 'sss','dan', ?, '')`


    var addAql = "INSERT INTO `history` (userId,userName,algorithm,percent,result,status,time,type,leftSrc,rightSrc) VALUES(?, ?, ?, ?, ?, ?, ?,?, ?,?)";
    var len = req.body.data.length;
    var i;
    var j = 0;
    for (i = 0; i < len; i++) {
        var sql_Params = [req.body.data[i].userId, req.body.data[i].userName,
            req.body.data[i].algorithm, req.body.data[i].percent, req.body.data[i].result,
            req.body.data[i].status, req.body.data[i].time, req.body.data[i].type,
            req.body.data[i].leftSrc, req.body.data[i].rightSrc];
        db.query(addAql, sql_Params, (err, result) => {
            if (err) {
                console.log('[INSERT ERROR]-', err.message);
                return;
            }
            // console.log('INSERT ID:', result.insertId);
            // console.log('i', req.body.data[0].userId);
            // console.log('iiii', i);


            console.log('i', i);
            console.log('result.insertId', result);

            //base64转换为图片文件本地存储
            // for (var j = 0; j < i; j++) {
            console.log('j', j);
            // var fs = require('fs');
            var path = config.uploadImagePath + result.insertId + '.jpg';
            var newBase64 = req.body.data[j].leftSrc.replace(/^data:image\/\w+;base64,/, "");
            var dataBuffer = new Buffer(newBase64, 'base64');
            // console.log('dataBuffer是否是对象：' + Buffer.isBuffer(dataBuffer));
            fs.writeFile(path, dataBuffer, (err) => {
                if (err) {
                    console.log(err);
                } else {
                    console.log('写入成功！')
                }
            })
            j++;
            // }
        })
    }


    //数据库自增id不需要插入，插入数据带上数据库字段

    // db.query(
    //     "INSERT INTO `history2` (userId,userName,algorithm,percent,result,status,time,type,leftSrc,rightSrc) VALUES ('32', 'admin', '10', 10, 'sasas', 1, 'dan', 'sss', 'llll', 'rrrr')"
    // )

    // 创建数据表

    // db.query(
    //     "CREATE TABLE history(" +
    //     "id int not null auto_increment," +       //数据库自增id
    //     "userId varchar(255)," +
    //     "userName varchar(255), " +
    //     "algorithm varchar(255), " +
    //     "percent int," +
    //     "result varchar(255), " +
    //     "status int, " +
    //     "time varchar(255),type varchar(255),leftSrc mediumblob,rightSrc mediumblob,primary key (id))", (err, result) => {
    //         if (err) {
    //             throw err;
    //         } else {
    //             console.log('创建表成功')
    //         }
    //     })
})

router.put('/', function (req, res, next) {
    // res.send('put status')
    console.log(req.body.data);

    var modSql = 'UPDATE history SET status = ?,userName = ?,type = ? WHERE id = ?';
    var modSql_params = [2, req.body.data.userName, req.body.data.type, req.body.data.id];
    db.query(modSql, modSql_params, (err, result) => {
        if (err) {
            console.log('[UPDATE ERROR]-', err.message);
            return;
        }
        // console.log('UPDATE affectedRows', result);
    })

    var exec = require('child_process').exec;
    var arg1 = req.body.data.id + '.jpg';
    var filename = config.pythonPath;
    var start = new Date().getTime();
    exec('python' + ' ' + filename + ' ' + arg1, (err, stdout, stderr) => {
        if (err) {
            console.log('stderr:', stderr);
        } else {
            var updateSql = 'UPDATE history SET status =?,percent = ? WHERE id = ?';
            var updateParams = [1, 100, req.body.data.id];
            db.query(updateSql, updateParams, (err, result) => {
                if (err) {
                    console.log('python update', err);
                    return;
                }
                var end = new Date().getTime();
                console.log('execute time', end - start);

                var sql = 'create table if not exists result(id int,isdr double,masNum double,origin varchar(255),vessel varchar(255),massvessel varchar(255))';
                db.query(sql, (err, result) => {
                    if (err) {
                        throw err;
                        return;
                    }

                    //线上环境
                    // var ftm = stdout.split('\n');
                    // len = ftm.length;
                    // var pythonResult = ftm[len - 2];
                    // console.log('stdout: ', pythonResult);
                    // var sqlParams = [req.body.data.id, pythonResult[1],pythonResult[0],
                    //     imgPath + req.body.data.id + '.jpg',
                    //     imgPath + req.body.data.id + '_vessel.jpg',
                    //     imgPath + req.body.data.id + '_massvessel.jpg']

                    var addAql = "INSERT INTO `result` (id,isdr,masNum,origin,vessel,massvessel) VALUES(?, ?, ?, ?, ?,?)";
                    var sqlParams = [req.body.data.id, 1.0, 1.0,
                        imgPath + req.body.data.id + '.jpg',
                        imgPath + req.body.data.id + '_vessel.jpg',
                        imgPath + req.body.data.id + '_massvessel.jpg']
                    db.query(addAql, sqlParams, (err, result) => {
                        if (err) {
                            throw err;
                            return;
                        }
                        console.log('stdout:', stdout);
                        res.send(stdout);
                    })
                    console.log('create result success', result);
                })
                // db.query(
                //     "CREATE TABLE history(" +
                //     "id int not null auto_increment," +       //数据库自增id
                //     "userId varchar(255)," +
                //     "userName varchar(255), " +
                //     "algorithm varchar(255), " +
                //     "percent int," +
                //     "result varchar(255), " +
                //     "status int, " +
                //     "time varchar(255),type varchar(255),leftSrc mediumblob,rightSrc mediumblob,primary key (id))", (err, result) => {
                //         if (err) {
                //             throw err;
                //         } else {
                //             console.log('创建表成功')
                //         }
                //     })

                // console.log('python success', result)
            })
        }
    })

})

module.exports = router;